package com.zsyc.util;

import com.zsyc.model.Word;
import com.zsyc.model.CodeQuestion;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import java.util.logging.Level;

/**
 * 文件导入工具类
 */
public class FileImporter {
    private static final Logger LOGGER = Logger.getLogger(FileImporter.class.getName());
    
    /**
     * 导入单词文件
     * 支持格式：每行一个单词，单词和释义用逗号或制表符分隔
     */
    public static List<Word> importWordsFromFile(File file) {
        List<Word> words = new ArrayList<>();
        
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
            
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.isEmpty() || line.startsWith("#")) {
                    continue; // 跳过空行和注释行
                }
                
                String[] parts = line.split("[,|\t]");
                if (parts.length >= 2) {
                    String englishWord = parts[0].trim();
                    String chineseMeaning = parts[1].trim();
                    
                    if (!englishWord.isEmpty() && !chineseMeaning.isEmpty()) {
                        words.add(new Word(englishWord, chineseMeaning));
                    }
                }
            }
            
            LOGGER.info("从文件 " + file.getName() + " 成功解析 " + words.size() + " 个单词");
            
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "导入单词文件失败: " + file.getName(), e);
        }
        
        return words;
    }
    
    /**
     * 导入代码题目文件
     * 支持格式：JSON格式的代码题目数据
     */
    public static List<CodeQuestion> importCodeQuestionsFromFile(File file) {
        List<CodeQuestion> questions = new ArrayList<>();
        
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
            
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
            
            // 简单的CSV格式解析，格式：语言,代码片段,正确答案,解释,错误类型
            String[] lines = content.toString().split("\n");
            for (String dataLine : lines) {
                dataLine = dataLine.trim();
                if (dataLine.isEmpty() || dataLine.startsWith("#")) {
                    continue;
                }
                
                String[] parts = dataLine.split(",");
                if (parts.length >= 5) {
                    String language = parts[0].trim();
                    String codeSnippet = parts[1].trim();
                    String correctAnswer = parts[2].trim();
                    String explanation = parts[3].trim();
                    String errorType = parts[4].trim();
                    
                    if (!language.isEmpty() && !codeSnippet.isEmpty()) {
                        questions.add(new CodeQuestion(language, codeSnippet, correctAnswer, explanation, errorType));
                    }
                }
            }
            
            LOGGER.info("从文件 " + file.getName() + " 成功解析 " + questions.size() + " 道代码题目");
            
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "导入代码题目文件失败: " + file.getName(), e);
        }
        
        return questions;
    }
    
    /**
     * 获取支持的文件扩展名
     */
    public static String[] getSupportedWordFileExtensions() {
        return new String[]{".txt", ".csv"};
    }
    
    public static String[] getSupportedCodeQuestionFileExtensions() {
        return new String[]{".txt", ".csv"};
    }
    
    /**
     * 验证文件是否为支持的类型
     */
    public static boolean isSupportedWordFile(File file) {
        String fileName = file.getName().toLowerCase();
        for (String ext : getSupportedWordFileExtensions()) {
            if (fileName.endsWith(ext)) {
                return true;
            }
        }
        return false;
    }
    
    public static boolean isSupportedCodeQuestionFile(File file) {
        String fileName = file.getName().toLowerCase();
        for (String ext : getSupportedCodeQuestionFileExtensions()) {
            if (fileName.endsWith(ext)) {
                return true;
            }
        }
        return false;
    }
}
